package com.hoso.android.bmilog;

import android.app.ListActivity;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.RemoteViews;

public class BMILogActivity extends ListActivity {
	static final String PREFERENCE_NAME = "BMI_LIST";
	static final String PREFERENCE_KEY = "PREFERENCE_KEY";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences preferences = getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);
        Uri uri = getIntent().getData();
        if(uri != null){
        	String[] measurements = uri.getQueryParameter("measurements").split(",");
        	String result = getString(R.string.label_height) + measurements[0] + ", "
        			+ getString(R.string.label_weight) + measurements[1] + ", "
        			+ getString(R.string.lael_bmi) + measurements[2];
        	SharedPreferences.Editor editor = preferences.edit();
        	editor.putString(PREFERENCE_KEY, preferences.getString(PREFERENCE_KEY, "") + result + "/");
        	editor.commit();
        	BMILogAppWidget.updateAppWidget(this);
        }
        setListAdapter(new ArrayAdapter<String>(this,
        		android.R.layout.simple_list_item_1,preferences.getString(PREFERENCE_KEY, "").split("/")));
        getListView().setTextFilterEnabled(true);
    }
    
    public static class BMILogAppWidget extends AppWidgetProvider{
    	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
    		
    		updateAppWidget(context);
    	}
    	public static void updateAppWidget(Context context){
    		AppWidgetManager manager = AppWidgetManager.getInstance(context);
    		RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.bmilog_widget_layout);
    		SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);
    		String[] logs = preferences.getString(PREFERENCE_KEY, "").split("/");
    		views.setTextViewText(R.id.last_log, logs[logs.length-1]);
    		manager.updateAppWidget(new ComponentName(context,BMILogAppWidget.class), views);
    	}
    }
}